<template>
  <div>

    <quill-editor
      ref="QuillEditor"
      v-model="content"
      :disabled="readonly"
      :options="editorOption"
      :style="{height:heigh+'px'}"
      @change="onEditorChange($event)" />
    <el-upload
      class="el-upload"
      :on-error="handleAvatarError"
      :on-success="handleAvatarSuccessImg"
      :before-upload="beforeUpload"
      :headers="headers"
      :action="action"
      accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PBG,.BMP"
      :show-file-list="false">
      <span class="icon"
        style="display: inline-block; ">
        <i
          class="el-icon-picture "></i>
      </span>
    </el-upload>
  </div>
</template>

<script>
import { HTTP_URI } from '@/api_new/api'
import store from '@/store'
import Quill from 'quill'
import { quillEditor } from 'vue-quill-editor'
import { ImageDrop } from 'quill-image-drop-module'
import ImageResize from 'quill-image-resize-module'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { toolbarOptions } from './toolbar'
Quill.register('modules/imageDrop', ImageDrop)
Quill.register('modules/imageResize', ImageResize)
const Size = Quill.import('attributors/style/size')
Size.whitelist = ['10px', '14px', '16px', '18px', '20px', '24px']
Quill.register(Size, true)
const Font = Quill.import('formats/font')
Font.whitelist = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'Times-New-Roman', 'sans-serif']
Quill.register(Font, true)
export default {
  name: 'Index',
  components: {
    quillEditor
  },
  props: {
    readonly: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    },
    heigh: {
      type: Number,
      default: 325
    },
    isPushContent: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      flag: true,
      action: HTTP_URI.UPLOADIMG,
      headers: {
        token: window.localStorage.getItem('token')
      },
      content: '',
      editorOption: {
        placeholder: '请输入',
        theme: 'snow',
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector('.el-upload').click()
                  // 触发element upload 单机事件
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          },
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        }
      },
      replyTo: ''
    }
  },
  watch: {
    value: {
      handler(val) {
        this.content = val
      },
      immediate: true
    }
  },
  methods: {
    onSelectd() {},
    getEditorValue() {
      return this.content
    },
    setEditorValue(content = '') {
      this.content = content
    },
    handleAvatarError() {
      this.$message.warning('网络繁忙，请稍后上传')
    },
    beforeUpload(file) {
      if (file.type == 'image/jpeg' || file.type == 'image/png') {
        const isLt10M = file.size / 1024 / 1024 < 10
        if (!isLt10M) this.$message.error('图片大小不能超过10M')
        return isLt10M
      } else {
        this.$message.error('图片格式错误')
        return false
      }
    },
    onEditorChange({ quill, html, text }) {
      this.content = html
      this.$emit('input', this.content)
      this.$emit('change', this.content)
    },
    handleAvatarSuccessImg(res, file) {
      if (file.status == 'success') {
        const quill = this.$refs.QuillEditor.quill
        console.log(quill.selection.savedRange.index)
        const length = quill.selection.savedRange.index
        // 向富文本内容中插入图片
        quill.insertEmbed(length, 'image', res.data.imageUrl)
        // quill.insertEmbed(length, 'image', res.data.url)
        // 移动焦点光标位置
        quill.setSelection(length + 1)
        // this.insertHtml('<img src=' + res.data.url + ' />')
      }
    },
    insertHtml(content) {
      // 设置编辑器获取焦点
      this.editor.events.focus()
      // 获取选定对象
      const selection = getSelection()
      // 判断是否有最后光标对象存在
      if (this.lastEditRange) {
        // 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
        selection.removeAllRanges()
        selection.addRange(this.lastEditRange)
      }
      // 插入内容
      this.editor.html.insert(content)
      // 记录最后光标停留位置
      this.lastEditRange = selection.getRangeAt(0)
    }
  }
}
</script>

<style>
@import url('./css/index.css');
.icon {
  font-size: 16px;
  color: #444;
  margin-right: 10px;
  position: absolute;
  top: 12px;
  background-color: #fefefe;
  left: 20px;
}
.icon:hover i {
  color: #1976d2;
}

.ql-container {
  height: 313px !important;
}
.quill-editor {
  line-height: normal !important;
}
</style>
